import Vue from 'vue'
import axios from 'axios'
import qs from "qs"
import {Message} from 'element-ui'
var instance = axios.create(
{
	baseURL:"http://127.0.0.1:80"
})

//情求拦截
instance.interceptors.request.use(
    config => {    
        let token = window.localStorage.getItem('token');
        console.log("每次请求前读取 Token=" + token)
        if (token) {
            config.headers.Authorization = "Bearer " + token;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

//响应拦截

instance.interceptors.response.use(
	//第一个参数是一个匿名函数作为参数变量,正常响应 HTTp状态码200
	response =>{
		console.log("正常响应 HTTP状态码:"+response.status);
		//resp/data.code != 200
		return response;
	},
	//第二个参数是一个匿名函数,出错了，非正常响应 HTTp状态码
	error =>{
		if(error.response){//如果spring boot 没有启动，就没有这个
			switch (error.response.status){
				case 401:
				Message.error("401 无权限.....");
					break;
				case 403:
				Message.error("401 无权限.....");
				default:
				Message.error(error.response.status+"系统在建设...");
					break;
			}
			
		}
		return Promise.reject(error.response.data)//继续往下执行
	}
);

//提交 4 中方式get post kv postFile 
//get 封装 支持2中凡是
//请求路径url  /api/adm/clz/findById?id=100   $get("/api/adm/clz/findById?id=100")
export let $get = (url,obj) =>{
	
	return instance.get(url,{params:obj})
}

//post 键值对
//请求路径url ,obj 是对象
//$postkv("/login",{username:'139001',password:'123'})
export let $postk = (url,obj) =>{
	let kv = qs.stringify(obj)
	
	let head = {headers : {'Content-Type':'application/x-www-form-urlencoded;chartset=utf8'}}
	return instance.post(url,kv,head)
}

//post 文件
//请求路径url ,FormData
//$postkv("/login",{username:'139001',password:'123'})
export let $postf = (url,formdata) =>{
	
	let head = {headers : {'Content-Type':'multipart/form-data'}};
	return instance.post(url,formdata,head)
}

//post json 对象或数组
//请求路径url ,（对象或数组）
//$postkv("/login",{username:'139001',password:'123'})
export let $postj = (url,obj) =>{
	let head = {headers : {'Content-Type':'application/json;chartset=utf8'}};
	return instance.post(url,obj,head);
}



